using System;
using System.Configuration;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Web;

using Geekees.Common.Exceptions;
using Geekees.App.HRAssistant.Core.Configuration;
using Geekees.App.HRAssistant.DataInterface.Common;
using Geekees.App.HRAssistant.Data.NHibernateSessionMgmt;

namespace Geekees.App.HRAssistant.BOL.Common
{

	public class FactoryManager : IFactoryManager
	{
		#region IFactoryManager Members

		public IDaoFactory GetDaoFactory()
		{
			string frameworkConfigPath = HttpContext.Current.Server.MapPath( "~/Config/FrameworkNHibernate.config" );
			IDaoFactory factory = new NHibernateDaoFactory( frameworkConfigPath );
			return factory;

			/*//uncomment the following code to enable dao configuration, you can switch amoung different daos by change DaoConfiguration section in web.config file.
			DaoSettingCollection dsc = ConfigurationManager.GetSection( "DaoConfiguration" ) as DaoSettingCollection;
			if( dsc == null )
				throw new BOLException( "Section 'DaoConfiguration' not found, please check the config file!" );
			
			DaoSetting ds = dsc.SingleDaoSetting();
			if( ds == null )
				throw new BOLException( "No Dao setting found, please check the config file!" );

			try
			{
				return CreateObject( ds.AssemblyName, ds.AssemblyTypeName, ds.ConnectionStr );
			}
			catch( Exception ex )
			{
				throw new BOLException( "Load Dao setting failed, Detail: " + ex.Message, ex );
			}
			*/
		}

		private IDaoFactory CreateObject( string assemblyName, string typeName, string connStr )
		{
			Assembly assembly;
			Type type;
			Object instance = null;
			IDaoFactory iFactory;

			//TODO: refractor, make flexible path.
			string completePath = HttpContext.Current.Server.MapPath("~/bin/" + assemblyName);
			assembly = Assembly.LoadFrom( completePath );
			type = assembly.GetType( typeName, true );
			instance = Activator.CreateInstance( type );
			iFactory = ( IDaoFactory )instance;
			return iFactory;
		}

		#endregion
	}
}
